package com.aloha.auth.interceptor;

import com.aloha.auth.support.AuthValidator;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhdai
 * @date 2023/11/9 22:06
 */
public class AuthInterceptor implements HandlerInterceptor {

    /**
     * 参数校验器的集合
     */
    private final List<AuthValidator> validators = new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 责任链模式
        for (AuthValidator validator : validators) {
            if (!validator.validate(request, response, handlerMethod)) {
                return false;
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    public AuthInterceptor addValidator(AuthValidator validator) {
        validators.add(validator);
        return this;
    }
}
